<?php
namespace app\common\model;

use think\Db;
use think\Model;

class Department extends Model
{
    protected $insert = ['create_time'];
    protected $update = ['update_time'];

    /**
     * 创建时间
     * @return bool|string
     */
    protected function setCreateTimeAttr()
    {
        return date('Y-m-d H:i:s');
    }

    /**
     * 更新时间
     * @return bool|string
     */
    protected function setUpdateTimeAttr()
    {
        return date('Y-m-d H:i:s');
    }

    protected static function init()
    {
        parent::init();

        self::event('after_insert', function ($department) {
            $pid = $department->pid;
            if ($pid > 0) {
                $parent         = self::get($pid);
                $department->path = $parent->path . $pid . ',';
            } else {
                $department->path = 0 . ',';
            }

            $department->save();
        });

        self::event('after_update', function ($department) {
            $id   = $department->id;
            $pid  = $department->pid;
            $data = [];

            if ($pid == 0) {
                $data['path'] = 0 . ',';
            } else {
                $parent       = self::get($pid);
                $data['path'] = $parent->path . $pid . ',';
            }

            if ($department->where('id', $id)->update($data) !== false) {
                $children = self::all(['path' => ['like', "%{$id},%"]]);
                foreach ($children as $value) {
                    $value->path = $data['path'] . $id . ',';
                    $value->save();
                }
            }

        });
    }

}